<?php

namespace app\business\controller;

use app\business\model\AreasModel;
use app\business\model\BuyerModel;
use app\business\model\CustomerNatureModel;
use app\business\model\FollowModel;
use app\business\model\BuyerUserModel;
use app\business\model\IndustryCateModel;
use app\business\model\RongcuiIndustryTypeModel;
use app\user\model\UserModel;
use cmf\controller\AdminBaseController;

class BuyerController extends AdminBaseController
{
    private $cate;
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->cate = [4, 5, 6, 7];
    }

    /**
     * 买家列表
     * @adminMenu(
     *     'name'   => '买家列表',
     *     'parent' => 'business/LicensePlate/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '买家列表',
     *     'param'  => ''
     * )
     */
    function index()
    {
        $where = [];
        $uid = cmf_get_current_admin_id();
        if ($uid != 1) {
            $users = implode(',', getUsersForRole($uid));
            $where['cbuser.uid|mbuser.uid|sbuser.uid'] = ['in', $users];
        }

        if (input('category')) {
            $where['ctype.cate_id'] = ['in', input('category')];
        }else{
            $where['ctype.cate_id'] = ['not in', $this->cate];
        }
        if (input('source')) {
            $where['buyer.source'] = input('source');
        }
        if (input('is_done')) {
            $where['buyer.is_done'] = input('is_done',0,'intval') - 1;
        }
        if (input('start_time')) {
            $where['buyer.createtime'] = ['gt', strtotime(input('start_time'))];
        }
        if (input('end_time')) {
            $endtime = strtotime(input('end_time'));
            $datetime = strtotime(date('Y-m-d', $endtime));
            if ($endtime == $datetime) {
                $endtime += 86399;
            }
            if (isset($where['buyer.createtime'])) {
                $where['buyer.createtime'] = ['BETWEEN', [strtotime(input('start_time')), $endtime]];
            } else {
                $where['buyer.createtime'] = ['lt', $endtime];
            }
        }
        if (input('keyword')) {
            $keyword = input('keyword');
            $where['buyer.name|buyer.phone|buyer.remark|cuser.user_nickname|muser.user_nickname'] = ['like', "%$keyword%"];
        }

        $buyerModel = new BuyerModel();
        $lists = $buyerModel
            ->alias('buyer')
            ->join('__INDUSTRY_TYPE__ ctype', 'buyer.id = ctype.pid')
            ->join('__BUYER_USER__ cbuser', 'buyer.id = cbuser.pid and cbuser.level = 1', 'left')//创建
            ->join('__BUYER_USER__ mbuser', 'buyer.id = mbuser.pid and mbuser.level = 2', 'left')//负责
            ->join('__BUYER_USER__ sbuser', 'buyer.id = sbuser.pid and sbuser.level = 3', 'left')//分享

            ->join('__USER__ cuser', 'cbuser.uid = cuser.id', 'left')
            ->join('__USER__ muser', 'mbuser.uid = muser.id', 'left')
            ->group('buyer.id')
            ->where($where)
            ->field([
                'buyer.*',
//                'cate.name as cname',
                'cuser.user_nickname as cuname',
                'muser.user_nickname as muname',
            ])
            ->order('buyer.createtime desc,buyer.id desc')
            ->paginate();

        $industryCateModel = new IndustryCateModel();
        $cate = $industryCateModel->where([
            'status' => 1,
            'parent_id' => ['neq', 0],
            'id' => ['not in', $this->cate],
            'is_del' => 0
        ])->order('parent_id,list_order,id')->select();

        $customerNatureModel = new CustomerNatureModel();
        $source = $customerNatureModel->where([
            'type' => 2,
            'is_del' => 0
        ])->field('id,name')->select();

        $where_r = input();
        $lists->appends($where_r);
        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('source', $source);
        $this->assign('where_r', $where_r);
        $this->assign('page', $page);
        $this->assign('cate', $cate);
        return $this->fetch();
    }

    /**
     * 添加
     * @adminMenu(
     *     'name'   => '添加',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加',
     *     'param'  => ''
     * )
     */
    function add()
    {
        if ($this->request->isPost()) {
            $this->addPost();
        }
        $industryCateModel = new IndustryCateModel();
        $cate = $industryCateModel->where([
            'status' => 1,
            'parent_id' => ['neq', 0],
            'id' => ['not in', $this->cate],
            'is_del' => 0
        ])->order('parent_id,list_order,id')->select();
        $areas = new AreasModel();
        $areaslist = $areas->where(['parentid' => 0])->order('sort')->select()->toArray();

        $this->assign('cate', $cate);
        $this->assign('areaslist', $areaslist);
        return $this->fetch();
    }

    private function addPost()
    {
        $buyerModel = new BuyerModel();
        $arrData = $this->request->post();

        $arrData['createtime'] = strtotime($arrData['createtime']);
        if (!$arrData['createtime']) {
            $arrData['createtime'] = time();
        }
        $cids = explode(',', $arrData['cid']);
        if (!$cids) {
            $this->error('行业类别不能为空');
        }

        $industryCateModel = new IndustryCateModel();
        $cate = $industryCateModel->find($arrData['cid']);
        $arrData['cname'] = $cate['name'];

        $result = $buyerModel->allowField(true)->validate(true)->save($arrData);
        if ($result) {
//            $buyerModel->where(['id' => $buyerModel->id])->update(['no' => 'PRO' . ($buyerModel->id + 1853850)]);
            $data = [];
            foreach ($cids as $cid) {
                $data[] = [
                    'pid' => $buyerModel->id,
                    'cate_id' => $cid,
                    'level' => 1
                ];
            }

            $industryTypeModel = new RongcuiIndustryTypeModel();
            $industryTypeModel->allowField(true)->saveAll($data);
            $buyerUserModel = new BuyerUserModel();
            $buyerUserModel->allowField(true)->saveAll([
                ['pid' => $buyerModel->id, 'uid' => cmf_get_current_admin_id(), 'level' => 1],
                ['pid' => $buyerModel->id, 'uid' => $arrData['manager'], 'level' => 2],
            ]);
            $this->success(lang("ADD_SUCCESS"), url("buyer/index"));
        } else {
            $this->error($buyerModel->getError());
        }
    }

    /**
     * 编辑买家
     * @adminMenu(
     *     'name'   => '编辑买家',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑买家',
     *     'param'  => ''
     * )
     */
    function edit()
    {
        $id = $this->request->param('id', 0, 'intval');
        $buyerModel = new BuyerModel();
        $result = $buyerModel
            ->alias('buyer')
            ->join('__USER__ user', 'buyer.manager = user.id', 'left')
            ->join('__CUSTOMER_NATURE__ nature', 'buyer.source = nature.id and nature.type = 2', 'left')
            ->join('__CUSTOMER_NATURE__ nature_level', 'buyer.customer_level = nature_level.id and nature_level.type = 3', 'left')
            ->join('__CUSTOMER_NATURE__ ntru', 'buyer.nature = ntru.id and ntru.type = 7', 'left')
            ->field([
                'buyer.*',
                'user.user_nickname as mname',
                'nature.name as nname',
                'nature_level.name as level_name',
                'ntru.name as nature_name'
            ])
            ->where(['buyer.id' => $id])->find();

        $industryCateModel = new IndustryCateModel();
        $cate = $industryCateModel->where([
            'status' => 1,
            'parent_id' => ['neq', 0],
            'id' => ['not in', $this->cate],
            'is_del' => 0
        ])->order('parent_id,list_order,id')->select();

        $areas = new AreasModel();
        $areaslist = $areas->where(['parentid' => 0])->order('sort')->select()->toArray();

        $this->assign('areaslist', $areaslist);
        $this->assign('cate', $cate);
        $this->assign('result', $result);
        return $this->fetch();
    }

    /**
     * 编辑买家提交
     * @adminMenu(
     *     'name'   => '编辑买家提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑买家提交',
     *     'param'  => ''
     * )
     */
    function editPost()
    {
        $buyerModel = new BuyerModel();
        $arrData = $this->request->post();

        $arrData['createtime'] = strtotime($arrData['createtime']);
        if (!$arrData['createtime']) {
            $arrData['createtime'] = time();
        }

        $cids = explode(',', $arrData['cid']);
        if (!$cids) {
            $this->error('行业类别不能为空');
        }
        $data = [];
        foreach ($cids as $cid) {
            $data[] = [
                'pid' => $arrData["id"],
                'cate_id' => $cid,
                'level' => 1
            ];
        }
        $industryCateModel = new IndustryCateModel();
        $cate = $industryCateModel->find($arrData['cid']);
        $arrData['cname'] = $cate['name'];

        $result = $buyerModel->allowField(true)->validate(true)->save($arrData, ["id" => $arrData["id"]]);
        if ($result !== false) {
            $industryTypeModel = new RongcuiIndustryTypeModel();
            $industryTypeModel->where(['pid' => $arrData['id'], 'level' => 1])->delete();
            $industryTypeModel->allowField(true)->saveAll($data);

            $buyerUserModel = new BuyerUserModel();
            $buyerUserModel->allowField(true)->save(['uid' => $arrData['manager']], ['pid' => $buyerModel->id, 'level' => 2]);

            $this->success(lang("EDIT_SUCCESS"), url("Buyer/index"));
        } else {
            $this->error($buyerModel->getError());
        }
    }

    /**
     * 买家跟进
     * @adminMenu(
     *     'name'   => '买家跟进',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '买家跟进',
     *     'param'  => ''
     * )
     */
    function follow()
    {
        $pid = $this->request->param('pid', 0, 'intval');
        if (!$pid) {
            $this->error('非法访问');
        }
        $followModel = new FollowModel();
        $where = ['type' => 2, 'pid' => $pid];
        $lists = $followModel->where($where)->order(['id desc'])->paginate(10);
        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('page', $page);
        $this->assign('pid', $pid);
        return $this->fetch();
    }

    /**
     * 添加买家跟进
     * @adminMenu(
     *     'name'   => '添加买家跟进',
     *     'parent' => 'follow',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加买家跟进',
     *     'param'  => ''
     * )
     */
    function add_follow()
    {
        $pid = $this->request->param('pid', 0, 'intval');
        if (!$pid) {
            $this->error('非法访问');
        }
        $this->assign('pid', $pid);
        return $this->fetch();
    }

    /**
     * 添加买家跟进提交
     * @adminMenu(
     *     'name'   => '添加买家跟进提交',
     *     'parent' => 'follow',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加买家跟进提交',
     *     'param'  => ''
     * )
     */
    function add_followPost()
    {
        $followModel = new FollowModel();
        $arrData = $this->request->post();

        $time = time();
        $arrData['create_time'] = $time;
        $arrData['type'] = 2;
        $arrData['uid'] = cmf_get_current_admin_id();
        $arrData['next_time'] = strtotime($arrData['next_time']);
        if ($arrData['next_time'] < $time) {
            $arrData['next_time'] = 0;
        }
        if (!$arrData['pid']) {
            $this->error('非法访问');
        }

        $result = $this->validate($arrData, 'Follow');
        if ($result !== true) {
            $this->error($result);
        }

        $result = $followModel->allowField(true)->insertGetId($arrData);
        if ($result) {
            $buyerModel = new BuyerModel();
            $buyerModel->where(['id' => $arrData['pid']])->update([
                'evolve' => $arrData['remark'],
                'newtime' => $time,
                'nexttime' => $arrData['next_time']
            ]);
        }

        $this->success(lang("ADD_SUCCESS"), url("buyer/follow", ['pid' => $arrData['pid']]));
    }

    /**
     * 编辑买家跟进
     * @adminMenu(
     *     'name'   => '编辑买家跟进',
     *     'parent' => 'follow',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑买家跟进',
     *     'param'  => ''
     * )
     */
    function edit_follow()
    {
        $id = $this->request->param('id', 0, 'intval');
        $followModel = new FollowModel();
        $result = $followModel->where(['id' => $id])->find();

        $this->assign('result', $result);
        return $this->fetch();
    }

    /**
     * 编辑买家跟进提交
     * @adminMenu(
     *     'name'   => '编辑买家跟进提交',
     *     'parent' => 'follow',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑买家跟进提交',
     *     'param'  => ''
     * )
     */
    function edit_followPost()
    {
        $followModel = new FollowModel();
        $arrData = $this->request->post();

        $time = time();
        $arrData['next_time'] = strtotime($arrData['next_time']);
        if ($arrData['next_time'] < $time) {
            $arrData['next_time'] = 0;
        }

        $result = $this->validate($arrData, 'Follow.edit');
        if ($result !== true) {
            $this->error($result);
        }

        $result = $followModel->allowField(true)->where(["id" => $arrData["id"]])->update($arrData);
        if ($result) {
            $new = $followModel->where(['type' => 1, 'pid' => $arrData['pid']])->max('id');
            if ($new == $arrData['id']) {
                $buyerModel = new BuyerModel();
                $buyerModel->where(['id' => $arrData['pid']])->update([
                    'evolve' => $arrData['remark'],
                    'newtime' => $time,
                    'nexttime' => $arrData['next_time']
                ]);
            }
        }

        $this->success(lang("EDIT_SUCCESS"), url("buyer/follow", ['pid' => $arrData['pid']]));
    }

    function done()
    {
        $id = $this->request->param('id',0,'intval');
        if(!$id) {
            $this->error('参数错误');
        }

        $where = [];
        $uid = cmf_get_current_admin_id();
        if ($uid != 1) {
            $users = implode(',', getUsersForRole($uid));
            $where['cbuser.uid|mbuser.uid'] = ['in', $users];
        }
        $where['buyer.id'] = $id;

        $buyerModel = new BuyerModel();
        $buyer = $buyerModel
            ->alias('buyer')
            ->join('__BUYER_USER__ cbuser', 'buyer.id = cbuser.pid and cbuser.level = 1', 'left')//创建
            ->join('__BUYER_USER__ mbuser', 'buyer.id = mbuser.pid and mbuser.level = 2', 'left')//负责
//            ->join('__BUYER_USER__ sbuser', 'buyer.id = sbuser.pid and sbuser.level = 3', 'left')//分享

            ->join('__USER__ cuser', 'cbuser.uid = cuser.id')
            ->join('__USER__ muser', 'mbuser.uid = muser.id')
            ->where($where)
            ->field([
                'buyer.id',
            ])
            ->find();
        if(!$buyer) {
            $this->error('非法操作');
        }

        $buyerModel->save([
            'is_done' => 1
        ],['id'=>$id]);
        $this->success('处理完成');
    }

    /**
     * 记录分配
     * @adminMenu(
     *     'name'   => '记录分配',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '记录分配',
     *     'param'  => ''
     * )
     */
    function allot()
    {
        $check_ids = $this->request->param('check_ids', '');
        $buyerUserModel = new BuyerUserModel();
        if ($this->request->isPost()) {
            $ids = $this->request->param('ids', 0, 'intval');
            $buyerUserModel->allowField(true)->save(['uid' => $ids], [
                'pid' => ['in', $check_ids],
                'level' => 2
            ]);
            $buyerModel = new BuyerModel();
            $buyerModel->save([
                'manager' => $ids
            ], [
                'id' => ['in', $check_ids],
            ]);
            $this->success('设置成功');
        } else {
            $userModel = new UserModel();

            $where = [];
            $uid = cmf_get_current_admin_id();
            $flag = false;
            if ($uid != 1) {
                $roles = db('role_user')
                    ->where(['user_id' => $uid])
                    ->column('role_id');

                $role_deps = get_role_department($roles, 'data_to_all_user');
                foreach ($role_deps as $role_dep) {
                    if ($role_dep['data_to_all_user']) {
                        $flag = true;
                    }
                }
            }

            if ($uid != 1 && !$flag) {
                $where['dep.id'] = ['in', getUsersGroup($uid)];
            }
            $where['user_status'] = ['neq', 0];

            $lists = $userModel
                ->alias('user')
                ->join('__DEPARTMENT_USER__ dep_user', 'user.id = dep_user.user_id')
                ->join('__DEPARTMENT__ dep', 'dep_user.dep_id = dep.id')
                ->field([
                    'user.*',
                    'dep.name as dep_name,dep.id as dep_id'
                ])->where($where)->select();

            $users = $buyerUserModel->where([
                'pid' => ['in', $check_ids],
                'level' => 2
            ])->column('uid');

            $this->assign('lists', $lists);
            $this->assign('users', $users);
            return $this->fetch();
        }
    }

    /**
     * 记录分享
     * @adminMenu(
     *     'name'   => '记录分享',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '记录分享',
     *     'param'  => ''
     * )
     */
    function share()
    {
        $check_ids = $this->request->param('check_ids', '');
        $buyerUserModel = new BuyerUserModel();
        if ($this->request->isPost()) {
            $ids = $this->request->param('ids', '');
            $users = $buyerUserModel->where([
                'pid' => ['in', $check_ids],
                'level' => 3
            ])->select()->toArray();

            $buyerUserModel
                ->where([
                    'level' => 3,
                    'pid' => ['in', $check_ids]
                ])->delete();

            $ids = explode(',', $ids);
            $check_ids = explode(',', $check_ids);

            $data = [];
            foreach ($ids as $id) {
                foreach ($check_ids as $check_id) {
                    $data[] = [
                        'pid' => $check_id,
                        'uid' => $id,
                        'level' => 3
                    ];
                }
            }
            $buyerUserModel->allowField(true)->saveAll($data);
            $this->success('设置成功');
        } else {
            $userModel = new UserModel();

            $where = [];
            $uid = cmf_get_current_admin_id();
            $flag = false;
            if ($uid != 1) {
                $roles = db('role_user')
                    ->where(['user_id' => $uid])
                    ->column('role_id');

                $role_deps = get_role_department($roles, 'data_to_all_user');
                foreach ($role_deps as $role_dep) {
                    if ($role_dep['data_to_all_user']) {
                        $flag = true;
                    }
                }
            }

            if ($uid != 1 && !$flag) {
                $where['dep.id'] = ['in', getUsersGroup($uid)];
            }
            $where['user_status'] = ['neq', 0];

            $lists = $userModel
                ->alias('user')
                ->join('__DEPARTMENT_USER__ dep_user', 'user.id = dep_user.user_id')
                ->join('__DEPARTMENT__ dep', 'dep_user.dep_id = dep.id')
                ->field([
                    'user.*',
                    'dep.name as dep_name,dep.id as dep_id'
                ])->where($where)->select();

            $users = $buyerUserModel->where([
                'pid' => ['in', $check_ids],
                'level' => 3
            ])->column('uid');

            $this->assign('lists', $lists);
            $this->assign('users', $users);
            return $this->fetch();
        }
    }

    function change() {
        $cate_id = $this->request->param('cate_id',0,'intval');
        $id = $this->request->param('id',0,'intval');

        $industryCateModel = new IndustryCateModel();
        $cate = $industryCateModel->where([
            'id' => $cate_id
        ])->find();
        if(!$cate) {
            $this->error('改分类不存在！');
        }

        db('industry_type')->where([
            'pid' => $id
        ])->delete();

        $buyerModel = new BuyerModel();
        $buyerModel->save(['cid'=>$cate_id,'cname' => $cate['name']],[
            'id' => $id
        ]);

        db('industry_type')->insert([
            'pid' => $id,
            'cate_id' => $cate_id,
        ]);
        $this->success('设置成功！');
    }
}